﻿using LibNiconico.NiconicoApi.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace LibNiconico.NiconicoApi.Alert
{
    internal class NiconicoAlertClient : NicoXmlSocketCommentClient,INiconicoAlertClient
    {

        private NiconicoAlertConnectionInfo connectionInfo;

        public async Task ConnectAsync()
        {
            await base.ConnectAsync(this.connectionInfo, new NiconicoAlertConnectionExtentionInfo()).ConfigureAwait(false);
        }


        internal NiconicoAlertClient(NiconicoAlertConnectionInfo connectionInfo) : this(connectionInfo, SynchronizationContext.Current) { }

        internal NiconicoAlertClient(NiconicoAlertConnectionInfo connectionInfo, SynchronizationContext synchronizationContext)
            : base(null, null, synchronizationContext) 
        {

            this.connectionInfo = connectionInfo;

        }

        public event ReceiveNicoAlertNotificationMessageHandler Received;


        public override void Dispose()
        {
            Received = null;
            base.Dispose();
        }

        protected override void OnReadChat(IEnumerable<XElement> messages)
        {
            var chats = new List<NiconicoAlertNotificationMessage>();
            foreach (var message in messages)
            {
                this.ReadXmlMessage(message, (chatMessage) =>
                {
                    var chat = NiconicoAlertNotificationMessage.Parse(chatMessage);

                    if (!string.IsNullOrEmpty(chat.Id))
                    {
                        chats.Add(chat);
                    }
                });
                

            }

            

            if (Received != null && chats.Count > 0) Received(new NicoAlertNotificationMessageReceiveArgs(chats));
        }

        protected override void OnProtectedClose(string reason, Exception e)
        {
           
        }

        protected override void OnProtectedReadException(Exception e)
        {
            
        }

        protected override void OnProtectedReadChatResult(System.Xml.Linq.XElement message)
        {
           
        }

        protected override void OnProtectedReadThread(System.Xml.Linq.XElement message)
        {
            
        }
    }
}
